//
//  AppController.m
//  VidCrusher
//
//  Created by Cemil Browne on 4/06/08.
//  Copyright 2008 Cemil Browne. All rights reserved.
//
/*
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/ 

#import "AppController.h"

@implementation AppController


// Main init function for AppController - just set the arrays, really

-(id) init
{
	[super init];
	[self setVideoTypes:[NSArray arrayWithObjects:@"TV Show", @"Movie", @"Music Video", nil]];
	[self setCompressionTypes:[NSArray arrayWithObjects:@"iPhone", @"iPod", @"Apple TV", nil]];
	return self;
}

// Run the about panel
- (IBAction) runAboutPanel:(id)sender
{
	NSDictionary *options;
    NSImage *img;
    img = [NSImage imageNamed: @"NSApplicationIcon"];
    options = [NSDictionary dictionaryWithObjectsAndKeys:
			   @"© Cemil Browne, 2008", @"Copyright",
			   nil];
	
    [[NSApplication sharedApplication] orderFrontStandardAboutPanelWithOptions:options];
	
}

// After starting up, initialize a few key objects. 
-(void) awakeFromNib
{
	// Register the table view for receiving drag'n'drop
	[myTableView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]]; 

	// Set size of left drawer
	NSSize mySize; 
	mySize.width = 266;
	mySize.height = 165;
	[optionsDrawer setContentSize:mySize];
	
	// Set size of right drawer
	mySize.width = 234;
	[rightDrawer setContentSize:mySize];
	
	// Open drawers
	[optionsDrawer openOnEdge:NSMinXEdge];
	[rightDrawer openOnEdge:NSMaxXEdge];
	
	// Disable button
	[deleteAfterAdding setEnabled:NO];
}


// This is the receiver of the "begin compression button".  It starts the compression sequence. 
- (IBAction) beginCompression:(id) sender
{
	int i = 0;
	for(i=0;i<[fileMenu numberOfItems];i++)
	{
		[[fileMenu itemAtIndex:i] setEnabled:NO];
	}
	// Only compress if there are objects to compress, obviously. 
	if([[myArrayController arrangedObjects] count])
	{
		// Disable the compress drop down
		[compressFor setEnabled:NO];
		
		// Begin the compression sheet
		[NSApp beginSheet:compressionSheet modalForWindow:mainWindow modalDelegate:self didEndSelector:@selector(compressionSheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
		
		// Do the work
		[mainCompressionController beginCompressing];
	}
	else
	{
		return;
	}
}

// Toggle the "delete after adding" button's enabled status
- (IBAction) addToItunesClicked: (id) sender
{
	if([addToItunes state] == NSOnState)
	{
		[deleteAfterAdding setEnabled:YES];
	}
	else
	{
		[deleteAfterAdding setEnabled:NO];
	}
}

// After the compression sheet ends, re-enable the compressFor
- (void)compressionSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	int i = 0;
	for(i=0;i<[fileMenu numberOfItems];i++)
	{
		[[fileMenu itemAtIndex:i] setEnabled:YES];
	}
	[compressFor setEnabled:YES];
}

// The endCompression button was clicked in the sheet
- (IBAction) endCompression:(id) sender
{
	// shouldStop is a global variable that is read in the thread that does the video processing.  Setting it to 1 causes the video processing to stop. 
	shouldStop = 1;
	
	// End the sheet
	[NSApp endSheet:compressionSheet];
	[compressionSheet orderOut:self];
	
}

// Accessor Functions
- (NSArray *) compressionTypes
{
	return compressionTypes;
}
- (void)setCompressionTypes:(NSArray *)anArray
{
	compressionTypes = [anArray copy];
}

- (NSArray *) videoTypes
{
	return videoTypes;
}
- (void) setVideoTypes:(NSArray *) anArray
{
	videoTypes = [anArray copy];
}
// End accessor functions

// Add file dialog
- (IBAction)addFile:(id)sender
{
	// Standard file dialog
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	[panel setAllowsMultipleSelection:YES];
	[panel setCanChooseFiles:YES];
	[panel setCanChooseDirectories:YES];
	[panel beginSheetForDirectory:nil file:nil types:nil modalForWindow:myWindow modalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
// Add file dialog ended
- (void) openPanelDidEnd:(NSOpenPanel*)panel returnCode:(int)rc contextInfo:(void *) ctx
{
	// Add the files
	[self addFilesToController:[panel filenames]];
}

// Actually do the adding.  Check to make sure the files are good. 
- (void) addFilesToController:(NSArray *)someFiles
{
	NSFileManager *myFM = [NSFileManager defaultManager];
	BOOL exists, isDir;
	if(someFiles == nil)
	{
		return;
	}
	if([someFiles count] < 1)
	{
		return;
	}
	
	for (int i=0; i<[someFiles count]; i++) 
	{
		exists = [myFM fileExistsAtPath:[someFiles objectAtIndex:i] isDirectory:&isDir];
		
		// As long as it exists and is not a directory, add it. 
		if(exists  && !isDir)
		{
			VideoItem *temp = [[VideoItem alloc] initWithFileName:[someFiles objectAtIndex:i]]; // This will actually open the file.  If video can't be opened, it will return nil. 
			if(temp != nil)
			{
				[myArrayController addObject:temp];
			}
		}
	}
}


// Pick a destination path
- (IBAction) browseDestinationPath:(id) sender
{
	// Standard directory dialog
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	[panel setAllowsMultipleSelection:NO];
	[panel setCanChooseFiles:NO];
	[panel setCanChooseDirectories:YES];
	[panel beginSheetForDirectory:nil file:nil types:nil modalForWindow:myWindow modalDelegate:self didEndSelector:@selector(browseDestinationPanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
// Set destination path
- (void) browseDestinationPanelDidEnd:(NSOpenPanel*)panel returnCode:(int)rc contextInfo:(void *) ctx
{
	[path setStringValue:[[panel filenames] objectAtIndex:0]];
}


// Accept drag and drop.  Validate every drop for files.  Later function will test it for openability
- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation
{
	NSPasteboard* pboard = [info draggingPasteboard];
	if ( [[pboard types] containsObject:NSFilenamesPboardType] ) 
	{
        // This is where drag and drop happens
		NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
		[self addFilesToController:files];
    }
	return true;
}

// Validate every drop. 
- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op

{
	
    // Add code here to validate the drop
    return NSDragOperationEvery;
}

// Open drawer functions - straightforward. 
- (IBAction) openDrawer:(id)sender
{
	NSDrawerState state = [optionsDrawer state];
    if (NSDrawerOpeningState == state || NSDrawerOpenState == state) {
        [optionsDrawer close];
    } else {
        [optionsDrawer openOnEdge:NSMinXEdge];
    }
}
- (IBAction) openRightDrawer:(id)sender
{
	NSDrawerState state = [rightDrawer state];
    if (NSDrawerOpeningState == state || NSDrawerOpenState == state) {
        [rightDrawer close];
    } else {
        [rightDrawer openOnEdge:NSMaxXEdge];
    }
}

@end
